package com.mpsc.api.unit;

import java.io.*;
import java.util.List;

public class DocToHtmlUtil {


    private static String path = "d:/test/";
    private static String docxName = "测试docx.docx";
    private static String docName = "测试.doc";
    private static String imgPath = "d:/test/";

//    public static void main(String[] args) throws Exception {
//        readeWordToHtml(path + docxName);
//        // readeWordToHtml(path + docName);
//    }
//

    /**
     * @param filepath 待转换的文件
     * @return java.lang.String
     * @description 对文件进行word转换成html字符串返回
     */
//    public static String readeWordToHtml(String filepath) throws Exception {
//        //获取文件后缀doc、docx
//        String suffix = filepath.substring(filepath.lastIndexOf(".") + 1);
//
//        try {
//            if (suffix.equals("doc") || suffix.equals("DOC")) {
//                //解析doc文件，转化为html并返回
//                return docToHtml(filepath);
//            } else if (suffix.equals("docx") || suffix.equals("DOCX")) {
//                String result = "";
//                //1、将docx转化为doc，doc转化为html，回报格式错误
////                String docFilePath = DocxToDocUtil.docxTodoc(filepath);
////                String result = docToHtml(docFilePath);
////                File docFile = new File(docFilePath);
////                docFile.delete();
//               /* 2、直接将docx转化为html，解析之后的内容没有格式
//                return analyzeDocx(filepath);*/
//                //3、直接将docx转化为html，解析之后的内容格式错误
//                //return docx2Html(filepath, null);
//                // return docxToHtml(filepath);
//                //return docxToHtml2(filepath);
//
//                return result;//docxToHtml3(path,docxName);
//            } else {
//                return "传入的文件格式类型错误，请上传doc，docx";
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//            System.out.println("文件格式错误!");
//            return "文件格式错误!";
//        } catch (Throwable throwable) {
//            throwable.printStackTrace();
//            return null;
//        }
//    }
//

    /**
     * docx转html
     *
     * @param path     docx文档所在文件夹路径
     * @param fileName docx文档名称
     * @return 转换后的html代码
     * @throws Throwable
     */
//    public static String docxToHtml3(String path, String fileName) throws Throwable {
//        String fileOutName = path + "new 6.html";
//        //加载word文档生成 XWPFDocument对象
//        XWPFDocument document = new XWPFDocument(new FileInputStream(path + fileName));
//        XHTMLOptions options = XHTMLOptions.create();
//
//        // 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
//        File imageFolder = new File(path + "/images/" + fileName);
//        options.setExtractor(new FileImageExtractor(imageFolder));
//        options.URIResolver(new FileURIResolver(imageFolder));
//
//        //将 XWPFDocument转换成XHTML
//        OutputStream out = new FileOutputStream(new File(fileOutName));
//        XHTMLConverter.getInstance().convert(document, out, options);
//
//        StringBuilder content = new StringBuilder();
//        File file = new File(fileOutName);
//        try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
//            String tempString;
//            while ((tempString = reader.readLine()) != null) {
//                content.append(tempString);
//            }
//            reader.close();
//            out.close();
//            //file.delete();
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//        String s = content.toString().replace(path, "/files/news/");
//        System.out.println(s);
//        return s;
//    }
//
    /**
     * docx格式word转换为html
     *
     * @param filepath   docx文件路径
     * @param outPutFile html输出文件路径
     * @throws IOException
     */
//    public static String docx2Html(String filepath, String outPutFile) throws Exception {
//        //加载word文档生成 XWPFDocument对象
//        FileInputStream fileInputStream = new FileInputStream(filepath);
//        XWPFDocument document = new XWPFDocument(fileInputStream);
//
//        //创建docx文件中图片存放地址
//        String picViewPath = filepath.substring(0, filepath.lastIndexOf(".")) + "/";
//        FileUtil.createFile(picViewPath);
//        // 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)
//        File imageFolder = new File(picViewPath);
//
//        XHTMLOptions options = XHTMLOptions.create();
//        options.setIgnoreStylesIfUnused(true);
//        options.setExtractor(new FileImageExtractor(imageFolder));
//        // URI resolver
//        options.URIResolver(new FileURIResolver(imageFolder));
//
////        将 XWPFDocument转换成XHTML
////        String fileOutName ="html文件地址";
////        OutputStream out = new FileOutputStream(new File(fileOutName));
////        XHTMLConverter.getInstance().convert(document, out, options);
//
//        //将 XWPFDocument转换成XHTML字符串
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
//        XHTMLConverter.getInstance().convert(document, out, options);
//        String result = out.toString();
//        out.close();
//        System.out.println(result);
//        return result;
//    }

//    public static String docxToHtml(String filepath) throws Exception {
//        //图片的保存目录
//        String picViewPath = filepath.substring(0, filepath.lastIndexOf(".")) + "/";
//        //创建文件夹
//        FileUtil.createFile(picViewPath);
//
//        File file = new File(filepath);
//        FileInputStream fileInputStream = new FileInputStream(file);
//        XWPFDocument document = new XWPFDocument(fileInputStream);
//        XHTMLOptions options = XHTMLOptions.create();
//        //图片提取
//        //图片路径
////        ImageManager imageManager = new ImageManager(new File(picPath), "");
////        options.setIgnoreStylesIfUnused(false);
////        options.setFragment(true);
////        options.setImageManager(imageManager);
//        File imageFolder = new File(picViewPath);
//        options.setExtractor(new FileImageExtractor(imageFolder));
//        // URI resolver
//        options.URIResolver(new FileURIResolver(imageFolder));
//        // 3) 将 XWPFDocument转换成XHTML
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
//
//        XHTMLConverter.getInstance().convert(document, out, options);
//        String result = new String(out.toByteArray());
//        out.close();
//        //String s = result.replaceAll("<img src=\"", "<img src=\"" + picViewPath);
//        System.out.println(result);
//        return result;//result.replaceAll("<img src=\"", "<img src=\"" + picViewPath);
//    }


    /**
     * 将docx转化为html
     * 暂时不支持超链接
     * https://www.csdn.net/tags/MtzaggwsNzI0NjktYmxvZwO0O0OO0O0O.html
     */
//    public static String analyzeDocx(String filepath) throws Exception {
//        //图片的保存目录
//        String picViewPath = filepath.substring(0, filepath.lastIndexOf(".")) + "/";
//        //创建图片的保存目录
//        FileUtil.createFile(picViewPath);//创建文件夹
//        StringBuilder sb = new StringBuilder();
//        try (InputStream in = new FileInputStream(filepath)) {
//            XWPFDocument xwpfDocument = new XWPFDocument(in);
//            List<XWPFParagraph> paragraphs = xwpfDocument.getParagraphs();
//            for (XWPFParagraph xwpfParagraph : paragraphs) {
//                List<XWPFRun> runs = xwpfParagraph.getRuns();
//                for (XWPFRun xwpfRun : runs) {
//                    CTR ctr = xwpfRun.getCTR();
//                    if (ctr.xmlText().contains("w:type=\"textWrapping\"")) {
//                        sb.append("<br>");//段内换行
//                        continue;
//                    }
//                    XmlCursor newCursor = ctr.newCursor();
//                    newCursor.selectPath("./*");
//                    while (newCursor.toNextSelection()) {
//                        XmlObject object = newCursor.getObject();
//                        if (object instanceof CTText) {
//                            // 文字
//                            CTText ctText = (CTText) object;
//                            if (ctText.isSetSpace()) {
//                                continue;// 先不支持超链接
//                            }
//                            String text = ctText.getStringValue();
//                            if (text != null && text.length() > 0) {
//                                sb.append(text);
//                            }
//                        } else if (object instanceof CTDrawing) {
//                            // 图片1
//                            CTDrawing drawing = (CTDrawing) object;
//                            CTInline[] inlineArray = drawing.getInlineArray();
//                            for (CTInline ctInline : inlineArray) {
//                                CTGraphicalObject graphic = ctInline.getGraphic();
//                                XmlCursor newCursor2 = graphic.getGraphicData().newCursor();
//                                newCursor2.selectPath("./*");
//                                while (newCursor2.toNextSelection()) {
//                                    XmlObject object2 = newCursor2.getObject();
//                                    if (object2 instanceof CTPicture) {
//                                        CTPicture picture = (CTPicture) object2;
//                                        //保存图片并返回图片链接
//                                        //<img src='d:/test/1649920371866image1.png'>
//                                        String imgHtml = imgHtml(xwpfDocument, picture.getBlipFill().getBlip().getEmbed(), picViewPath);
//                                        sb.append("<br>").append(imgHtml).append("<br>");
//                                    }
//                                }
//                            }
//                        }
//                    }
//                }
//                sb.append("<br>");// 分段
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        System.out.println(sb.toString());
//        return sb.toString();
//    }

    /**
     * 保存docx中的图片，并返回图片地址
     */
//    private static String imgHtml(XWPFDocument xwpfDocument, String blipID, String imgPath) {
//        XWPFPictureData pictureData = xwpfDocument.getPictureDataByID(blipID);
//        String imageName = pictureData.getFileName();
//        String newfilename = System.currentTimeMillis() + imageName;
//        byte[] bytev = pictureData.getData();
//        try (FileOutputStream fos = new FileOutputStream(imgPath + newfilename);) {
//            fos.write(bytev);// 此处保存图片后，变成可访问的http然后用<img>标签包裹
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return "<img src='" + imgPath + newfilename + "'>";
//    }
//
    /**
     * doc文档转化为html
     * （将doc文档中的图片放到doc文档名称文件夹下）
     *
     * @param filepath doc文档全路径
     * @return String
     */
//    public static String docToHtml(String filepath) throws Exception {
//        //图片的保存目录
//        String picViewPath = filepath.substring(0, filepath.lastIndexOf(".")) + "/";
//        //创建图片的保存目录
//        FileUtil.createFile(picViewPath);//创建文件夹
//        File file = new File(filepath);
//        FileInputStream fileInputStream = new FileInputStream(file);
//        HWPFDocument wordDocument = new HWPFDocument(fileInputStream);
//        WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
//                DocumentBuilderFactory.newInstance().newDocumentBuilder()
//                        .newDocument());
//        //设置图片在html中的地址
//        wordToHtmlConverter.setPicturesManager(new PicturesManager() {
//            @Override
//            public String savePicture(byte[] content, PictureType pictureType, String suggestedName,
//                                      float widthInches, float heightInches) {
//                String picViewPath = filepath.substring(0, filepath.lastIndexOf(".")) + "/";
//                return picViewPath + suggestedName;
//            }
//        });
//        wordToHtmlConverter.processDocument(wordDocument);
//        //保存图片
//        List pics = wordDocument.getPicturesTable().getAllPictures();
//        if (pics != null) {
//            for (int i = 0; i < pics.size(); i++) {
//                Picture pic = (Picture) pics.get(i);
//                try {
//                    pic.writeImageContent(new FileOutputStream(new File(picViewPath + pic.suggestFullFileName())));
//                } catch (FileNotFoundException e) {
//                    e.printStackTrace();
//                }
//            }
//        }
//        Document htmlDocument = wordToHtmlConverter.getDocument();
//        ByteArrayOutputStream out = new ByteArrayOutputStream();
//        DOMSource domSource = new DOMSource(htmlDocument);
//        StreamResult streamResult = new StreamResult(out);
//        TransformerFactory tf = TransformerFactory.newInstance();
//        Transformer serializer = tf.newTransformer();
//        serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");
//        serializer.setOutputProperty(OutputKeys.INDENT, "yes");
//        serializer.setOutputProperty(OutputKeys.METHOD, "html");
//        serializer.transform(domSource, streamResult);
//        String result = new String(out.toByteArray()).replaceAll("↵", "");
//        out.close();
//        System.out.println(result);
//        return result;
//    }
}
